package com.yuxi.controller.manager;

import com.yuxi.common.CreateImageCode;
import com.yuxi.common.SecurityUtil;
import com.yuxi.common.SkJsonResult;
import com.yuxi.common.StringUtil;
import com.yuxi.common.exception.ExceptionMessage;
import com.yuxi.common.token.AdminToken;
import com.yuxi.dto.LoginDTO;
import com.yuxi.dto.PswDTO;
import com.yuxi.enums.SysOperLogBusinessTypeEnum;

import com.yuxi.modelExt.AdminExt;
import com.yuxi.pubInter.IBaseService;
import com.yuxi.pubInter.aop.SystemLog;
import com.yuxi.pubInter.exception.BusinessException;
import com.yuxi.pubInter.exception.SkException;
import com.yuxi.service.IAdminService;
import com.yuxi.vo.AdminDetailVO;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashSet;

/**
*    @author sunke
*    @Date 2023-10-13 10:28:19
*    @description
*/

@Api(tags = "入口", description = "入口接口")
@Controller("backIndexController")
@RequestMapping("/manager/")
@Slf4j
public class IndexController extends ApiManageController {

    @Resource
    private IAdminService adminService;


    @ApiOperation(value = "判断是否过期", notes = "判断是否过期", httpMethod = "POST")
    @PostMapping("token")
    public SkJsonResult token() throws SkException {
        return SkJsonResult.ok();
    }

    @ApiOperation(value = "生成图片验证码", notes = "生成图片验证码", httpMethod = "GET")
    @GetMapping("imageCode")
    public void createImageCode(HttpServletRequest request, HttpServletResponse response, @ApiParam("时间戳") @RequestParam(required = false) String codeKey) throws Exception {


        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        CreateImageCode vCode = new CreateImageCode(150, 50, 4, 3);

        getRedisUtil().set(codeKey, vCode.getCode());


        vCode.write(response.getOutputStream());


    }

    @ApiOperation(value = "修改密码", notes = "修改密码", httpMethod = "POST")
    @PostMapping("/postPsw")
    @SystemLog(title = "修改密码", method = "postPsw", businessType = SysOperLogBusinessTypeEnum.UPDATE_TYPE)
    public SkJsonResult postPsw(@RequestBody PswDTO pswDTO, HttpServletRequest request) throws SkException {

        String adminId = getJwtsUtil().getAdminId(request);

        AdminExt admin = adminService.getDetail(adminId, new HashSet<>());

        if (!admin.getPassword().equalsIgnoreCase(SecurityUtil.generateUserPasswordByPswAndSalt(pswDTO.getOldPsw(), admin.getId()))) {
            throw new BusinessException(ExceptionMessage.PSW_ERROR);
        }
        admin.setPassword(SecurityUtil.generateUserPasswordByPswAndSalt(pswDTO.getPassword(), admin.getId()));
        adminService.update(admin);

        return SkJsonResult.ok();
    }






    @ApiOperation(value = "用户账号密码登录", notes = "用户账号密码登录接口", httpMethod = "POST")
    @PostMapping("/login")
    @SystemLog(title = "用户账号密码登录", method = "login", businessType = SysOperLogBusinessTypeEnum.GRANT_TYPE)
    public SkJsonResult<AdminDetailVO> login(@RequestBody LoginDTO dto, HttpServletRequest request, HttpServletResponse response) throws SkException {
        String imageCode = (String) getRedisUtil().get(dto.getCodeKey());
        log.debug("code:" + dto.getImageCode() + ",imageCode:" + imageCode + ",host:" + request.getHeader("Origin"));

        getRedisUtil().del(dto.getCodeKey());

        if (isImgCodeVerification()) {
            if (StringUtil.isEmpty(dto.getImageCode()) || !dto.getImageCode().equalsIgnoreCase(imageCode)) {
                throw new BusinessException(ExceptionMessage.IMAGE_CODE_ERROR);
            }
        }
        AdminExt admin = adminService.loginByUsernameAndPsw(dto.getUsername(), dto.getPassword());

        // 用户token
        AdminToken personToken = new AdminToken();
        personToken.setAdminId(admin.getId());
        personToken.setUsername(admin.getUsername());
        personToken.setTruename(admin.getTruename());

        getJwtsUtil().setAdminToken(personToken, response);

        return SkJsonResult.ok().setData(mapDetail(admin, AdminDetailVO.class));
    }

    @Override
    public IBaseService getBaseService() throws SkException {
        return null;
    }

    @Override
    public String getBaseRoute() throws SkException {
        return null;
    }


}
